/*  
 * @(#) BooleanTypeHandler.java Create on 2014-3-18 下午01:30:47   
 *   
 * Copyright 2014 by fibrlink.   
 */


package com.springdemo.tools;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 类型转换器 （ varchar['Y'/'N'] to boolean）
 * 实现TypeHandler接口 
 * 需要强调的是：为了让类型控制器起作用，必须在mapper.xml中对参数和结果的类型进行显示表明。 
 * @author charlin_yin
 * @date   2014-3-18
 */
@SuppressWarnings("rawtypes")
public class BooleanTypeHandler implements TypeHandler {

	@Override
	public Object getResult(ResultSet arg0, String arg1) throws SQLException {
		String str = arg0.getString(arg1);  
        Boolean rt = Boolean.FALSE;  
        if (str.equalsIgnoreCase("Y")){  
            rt = Boolean.TRUE;  
        }  
        return rt;   

	}

	@Override
	public Object getResult(ResultSet arg0, int arg1) throws SQLException {
		Boolean b = arg0.getBoolean(arg1);  
		return b == true ? "Y" : "N";  
	}

	@Override
	public Object getResult(CallableStatement arg0, int arg1) throws SQLException {
		return null;
	}

	@Override
	public void setParameter(PreparedStatement arg0, int arg1, Object arg2, JdbcType arg3) throws SQLException {
		Boolean b = (Boolean) arg2;  
		String value = (Boolean) b == true ? "Y" : "N";  
		arg0.setString(arg1, value); 
	}

}
